package org.study.plus.boot.config;

import com.baomidou.mybatisplus.extension.plugins.handler.TableNameHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

/**
 * 动态表名插件
 *
 * @author doveylovey
 * @version v1.0.0
 * @email 1135782208@qq.com
 * @date 2023年05月06日
 */
@Slf4j
public class MyTableNameHandler implements TableNameHandler {
    /**
     * 使用ThreadLocal维护每个请求线程的数据，避免多线程环境下数据冲突
     */
    private static final ThreadLocal<String> tableNameSuffixThreadLocal = new ThreadLocal<>();

    public static void setData(String suffix) {
        // 设置请求线程的month数据
        if (StringUtils.isNotBlank(suffix)) {
            tableNameSuffixThreadLocal.set(suffix);
        }
    }

    @Override
    public String dynamicTableName(String sql, String tableName) {
        log.info("[动态表名插件]当前SQL：{}", sql);
        String suffix = tableNameSuffixThreadLocal.get();
        if (StringUtils.isNotBlank(suffix)) {
            String tempTableName = tableName + suffix;
            log.info("[动态表名插件]suffix：{}，动态查询表：{}", suffix, tempTableName);
            tableNameSuffixThreadLocal.remove();
            return tempTableName;
        }
        return tableName;
    }
}
